﻿



create proc Products.SaveProductGroups (
	@ProductGroupID	uniqueidentifier = null output,
	@Name			nvarchar(255),
	@Description	nvarchar(400),
	@ParentGroupID	uniqueidentifier,
	@Status		int,	
	@ErrorMessage	nvarchar(400) output
)
as
begin

	if @ProductGroupID is null
	begin
		select @ProductGroupID = NEWID();
	end
	
	if @Name is null
	begin
		set @ErrorMessage = 'Name ist null';
		goto EndWithError;
	end
	if @Description is null
	begin
		set @ErrorMessage = 'Description ist null';
		goto EndWithError;
	end
	if @ParentGroupID is null
	begin
		set @ErrorMessage = 'ParentGroupID ist null';
		goto EndWithError;
	end
	if @Status is null
	begin
		set @ErrorMessage = 'Status ist null';
		goto EndWithError;
	end
	
	begin tran;
	
	
	
	with src 
	as
	(
		Select	@ProductGroupID 'ProductGroupID',
				@Name 'Name',
				@Description 'Description',
				@ParentGroupID 'ParentGroupID',
				@Status 'Status'
	)
	
	merge Products.datProductGroups as target
	using src
		on (target.ProductGroupID = src.ProductGroupID)
	when matched then 
		update SET	
				Name			= src.Name,
				[Description]	= src.[Description],
				ParentGroupID	= src.ParentGroupID,
				[Status]		= src.[Status]
				
	when not matched by target then
		insert (
			ProductGroupID,
			Name,
			[Description],
			ParentGroupID,
			[Status]
		)
		values (
			src.ProductGroupID,
			src.Name,
			src.[Description],
			src.ParentGroupID,
			src.[Status]
		);
		
	
	commit;
	return 0;
	
EndWithError:
	RAISERROR ( @ErrorMessage, 16, 1);
	return 1;	

end
GO


